package imv3.foo.server.handler;

import imv3.protocol.request.LoginRequestPacket;
import imv3.protocol.response.LoginResponsePacket;
import imv3.protocol.session.Session;
import imv3.util.SessionUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;
import java.util.UUID;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019-04-25 22:03
 * 既然选择了远方,便只顾风雨兼程
 */
@ChannelHandler.Sharable
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {

    public static final LoginRequestHandler INSTANCE = new LoginRequestHandler();

    protected LoginRequestHandler() {
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestPacket request) throws Exception {

        LoginResponsePacket response = new LoginResponsePacket();
        response.setVersion(request.getVersion());
        response.setUsername(request.getUsername());

        if (validate(request)) {
            response.setSuccess(true);
            String userId = randomUserId();
            response.setUserId(userId);
            System.out.println(new Date() + "[" + request.getUsername() + "]登录成功");
            SessionUtil.bind(new Session(userId, request.getUsername()), ctx.channel());
        } else {
            response.setSuccess(false);
            response.setReason("账号密码校验失败");
            System.out.println(new Date() + ": 登录失败");
        }

        ctx.channel().writeAndFlush(response);
    }

    private String randomUserId() {
        return UUID.randomUUID().toString().split("-")[0];
    }

    private boolean validate(LoginRequestPacket request) {
        return true;
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SessionUtil.unbind(ctx.channel());
    }
}
